package com.shujia.flink.window;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;

import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * @author shujia
 */
public class Demo3ProcessingTimeWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<String> lines = env.socketTextStream("master", 8888);

        DataStream<Tuple2<String, Integer>> kv = lines.map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT));

        KeyedStream<Tuple2<String, Integer>, String> keyBy = kv.keyBy(k -> k.f0);

        /*
         * SlidingEventTimeWindows： 滑动的事件时间窗口
         * SlidingProcessingTimeWindows：滑动的处理时间窗口
         * TumblingEventTimeWindows：滚动的事件时间窗口
         * TumblingProcessingTimeWindows：滚动处理时间窗口
         *
         * 如果使用事件时间窗口，数据中必须有一个时间字段
         */
        WindowedStream<Tuple2<String, Integer>, String, TimeWindow> windows = keyBy
                //每隔两秒计算最近十秒的数据
                .window(SlidingProcessingTimeWindows.of(Time.seconds(10), Time.seconds(2)));

        DataStream<Tuple2<String, Integer>> counts = windows.sum(1);

        counts.print();


        env.execute();


    }
}
